if (window.plus) {
    ready();
} else {
    document.addEventListener('plusready', ready, false);
}

$(function () {
    if (AGENT_CLIENT.WEB) {
        ready();
    }
})

function ready() {
    var html = [],
        thisPage = {},
        user = {},
        query = {
            index: 1,
            size: 10,
            query: '',
            search: {},
            sorting: {}
        },
        _myscroll = null,                    //滚动
        _thispage = null,                    //当前页
        _pullUp = null,
        _pullDown = null;

    var messagePage = function () {
        this.init();
    };

    messagePage.prototype = {

        init: function () {
        		this.addScroll();
            this.initData();
            this.bindEvent();
        },
        initData: function () {
            user = getLocalStorage(STORAGE_MANAGER.user);
            if (!user) {
                redirect("../account/login.html");
            }
            query.query = user.id;
            query.search.receive_type = 1;
            this.initMessage();
        },
        addScroll: function () {
            _pullUp = $("#pullUp");
            _pullDown = $("#pullDown");
            _pullDown.hide();
            _myscroll = new IScroll('#wrapper', {
                probeType: 2,
                scrollbars: true,
                mouseWheel: false,
                fadeScrollbars: true,
                bounce: true,
                interactiveScrollbars: false,
                shrinkScrollbars: 'scale',
                click: true,
                keyBindings: true,
                momentum: true
            });
            _myscroll.on("scrollEnd", function () {
                console.log("this.y=" + this.y);
                console.log("this.maxScrollY=" + this.maxScrollY);
                if ((this.y < 0) && (this.y == this.maxScrollY)) {
                    console.log("滚动到底部");
                    _pullUp.show();
                    setTimeout(function () {
                        query.index++;
                        thisPage.initMessage("add");
                    }, 500);
                } else if ((this.y == 0) && (this.y != this.maxScrollY)) {
                    console.log("滚动到顶部");
                    _pullDown.show();
                    setTimeout(function () {
                        query.index = 0;
                        thisPage.initMessage("renovate");
                    }, 500);
                }
            });
        },
        initMessage: function (action) {
            $.ajax({
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/message/inboxlists",
                async: true,
                data: query,
                headers: {token: user.token}
            }).done(function (data) {
                thisPage.loadMessage(data, action);
            }).fail(function (data) {
                var infor = JSON.parse(data);
                $.toast(infor.Message);
            });
        },
        loadMessage: function (data, action) {
            var data = JSON.parse(data);
            var messages = data.data;
            var length = messages.length;
            if (undefined == action && length == 0) {
                $("#dataList").html('<div class="zhanwushuju"><img src="../../images/zanwushuju.png"><br>暂无数据</div>');
            } else {
            	html = [];
                $.each(messages, function (i, item) {
                    var src = "";
                    var tip = "";
                    switch (item.type) {
                        //优惠券过期
                        case 1:
                            tip = "coupon.html";
                            src = "../../images/msg_coupon_overdue.png";
                            break;
                        //星粉秀审核
                        case 2:
                            tip = "../coin/coindetail.html?id=" + item.refinfo;
                            src = "../../images/msg_show.png";
                            break;
                        //订单发货及物流
                        case 3:
                            tip = "../order/detail.html?id=" + item.refinfo;
                            src = "../../images/msg_order.png";
                            break;
                        //领取优惠券
                        case 4:
                            tip = "coupon.html";
                            src = "../../images/msg_coupon.png";
                            break;
                        //领取星币
                        case 5:
                            tip = "show.html";
                            src = "../../images/msg_coin.png";
                            break;
                        //星粉秀发布通知
                        case 6:
                            tip = tip = "../coin/coindetail.html?id=" + item.refinfo;
                            src = "../../images/msg_show.png";
                            break;
                        default:
                            break;
                    }
                    html.push('<div name="messageItem" tip="' + item.id + "|" + tip + '" class="mbtopbottom sqshbg">');
                    html.push('<div class="with100 overflow">');
                    html.push('<p class="shxxbt1 mbbottom">');
                    var msgstatus = "";
                    if (item.status == 2) {
                        msgstatus = "display: none";
                    }
                    html.push('<span class="floatr mright5"><i class="hquan" name="unreadtip" style="margin-top: 16px;margin-left: -10px;' + msgstatus + '"></i><i class="iconfont icon-jiantou-right"></i></span>');
                    html.push('<span>' + item.title + '</span>');
                    html.push('</p>');
                    html.push('<dl class="cpxqxztop cpxqxztop1 mtop0">');
                    html.push('<dt><img src="' + src + '"></dt>');
                    html.push('<dd>');
                    html.push(item.content);
                    html.push('</dd>');
                    html.push('<dd class="wlxxlc wlxxlc5 floatr"><span class="huisezi">' + toDateString(item.create_time, 'yyyy-MM-dd hh:mm:ss') + '</b></span></dd>');
                    html.push('</dl>');
                    html.push('</div>');
                    html.push('</div>');
                });
            }
            if ("add" == action) {
                $(html.join('')).appendTo($("#dataList"));
            } else if (html.length > 0) {
                $("#dataList").html(html.join(''));
            }
            setTimeout(function () {
                _myscroll.refresh();
                _pullUp.hide();
                _pullDown.hide();
            }, 100);
        },
        bindEvent: function () {
            var thisPage = this;
            //回退
            $("#back").on("click", function () {
				if(AGENT_CLIENT.APP){
					plus.webview.getWebviewById("../mine/mylife.html").evalJS("reloadPage()");
					plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(4)");
				}else{
					redirect("mylife.html");
				}
            });

            //点击跳转
            $("#dataList").on("click", "div[name='messageItem']", function () {
                var params = $(this).attr('tip').split("|");
                var id = params[0], src = params[1];
                // 设置已读
                $(this).find("i[name=unreadtip]").hide();
                // 标记
                thisPage.readMassage(id,src);
                
            });
        },
        // 标记【收件箱】消息已读
        readMassage: function (msgid, src) {
            $.ajax({
                type: "PUT",
                url: CONFIG_MANAGER.RequstUrl + "v1/message/read/" + msgid,
                headers: {token: user.token}
            }).done(function (data) {
                if (AGENT_CLIENT.APP) {
                    plus.webview.getWebviewById("../mine/mylife.html").evalJS("refeshMsgCount()");
                }
                redirect(src);
            }).fail(function(data){
            	$.toast(data.responseJSON.Message);
            });


        }
    };

    thisPage = new messagePage();
}
